﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Threading.Tasks;
using IdentityModel;
using IdentityModel.Client;
using IdentityServer4.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using Swashbuckle.AspNetCore.Annotations;
using Web.Api.Server.Models;
using Web.Api.Server.ViewModels;

namespace Web.Api.Server.Controllers
{
    [SwaggerTag("登录授权管理")]
    [ApiController]
    [Route("[controller]")]
    public class AuthController : ControllerBase
    {
        private readonly IHttpClientFactory _http;

        public AuthController(IHttpClientFactory http)
        {
            _http = http;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <returns></returns>
        [HttpPost("Login")]
        [ProducesResponseType(typeof(ResponseViewModel<JObject>), 200)]
        public async Task<IActionResult> PostLogin(PostLoginViewModel viewModel)
        {
            var client = _http.CreateClient();
            TokenResponse response = await client.RequestTokenAsync(new TokenRequest
            {
                Address = "http://127.0.0.1:5000/connect/token",
                GrantType = GrantType.ResourceOwnerPassword,

                ClientId = "audit_client",
                ClientSecret = "7C109B83-2F30-440E-8F27-402D56475B16",

                Parameters =
                {
                    {"UserName", viewModel.Username},
                    {"Password", viewModel.Password}
                }
            });

            if (response.IsError)
            {
                return ApiResponse.Fail(response.ErrorDescription);
            }

            return ApiResponse.Ok(response.Json);
        }

        [HttpGet("RefreshToken")]
        [ProducesResponseType(typeof(ResponseViewModel<JObject>), 200)]
        public async Task<IActionResult> GetRefreshToken(string token)
        {
            if (string.IsNullOrEmpty(token))
            {
                return ApiResponse.Fail("请先登录");
            }

            var client = _http.CreateClient();

            TokenResponse response = await client.RequestTokenAsync(new TokenRequest
            {
                Address = "http://127.0.0.1:5000/connect/token",
                GrantType = OidcConstants.GrantTypes.RefreshToken,

                ClientId = "audit_client",
                ClientSecret = "7C109B83-2F30-440E-8F27-402D56475B16",

                Parameters = new Dictionary<string, string>
                {
                    { OidcConstants.TokenRequest.RefreshToken, token }
                }
            });

            if (response.IsError)
            {
                return ApiResponse.Fail(response.Error);
            }

            return ApiResponse.Ok(response.Json);
        }

        /// <summary>
        /// 检查用户登录
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [HttpGet("CheckUser")]
        [ProducesResponseType(typeof(ResponseViewModel<JObject>), 200)]
        public IActionResult GetCheckUser()
        {
            var user = new CheckUserViewModel
            {
                Username = User.Identity.Name,
                Roles = User.FindFirst(ClaimTypes.Role).Value
            };
            return ApiResponse.Ok(user);
        }
    }
}
